import Client from './sms'
import { eventBus } from './event-bus'

eventBus.on('send-sms', async (smsLogs) => {
  // console.log('Event received with data:', smsLogs);
  if (Array.isArray(smsLogs)) {
    const client = Client.createDysmsapiClient();
    for (const smslog of smsLogs) {
      if (smslog.status === 'INIT') {
        try {
          const response = await Client.sendSms(client, {
            phoneNumbers: smslog.mobile,
            signName: smslog.sign_name,
            templateCode: smslog.sms_code,
            templateParam: smslog.template_param
          });

          if (response.statusCode === 200) {
            if (response.body.code === 'OK') {
              smslog.status = 'SUCCESS';
              smslog.result = response.body.message;
            } else {
              smslog.status = 'FAILED';
              smslog.result = response.body.message;
            }
          } else {
            smslog.status = 'FAILED';
            smslog.result = response.body.message;
          }
        } catch (e) {
          console.error(e)
          smslog.status = 'FAILED';
          smslog.result = e.message;
        }

        await smslog.save();
      }
    }
  }
});
